{% extends "chat_base.html" %}

{% block "title" %}using subscribe-user{% endblock %}

{% block introduction %}
<p>Point a second browser onto this URL, login as <em>mary</em> or <em>john</em> and check for message synchronization.</p>
{% endblock introduction %}


{% block control_panel %}
	<button class="btn btn-primary" id="send_message">Send message</button>
	to
	<select class="form-control" id="user" style="display: inline-block; width: auto;">
	{% for user in users %}
		<option value="{{ user.username }}">{% firstof user.get_full_name user.username %}</option>
	{% endfor %}
	</select>
{% endblock control_panel %}

{% block script_panel %}
<script type="text/javascript">
	jQuery(document).ready(function($) {
		var ws4redis = WS4Redis({
			uri: '{{ WEBSOCKET_URI }}foobar?subscribe-user',
			receive_message: receiveMessage,
			heartbeat_msg: {{ WS4REDIS_HEARTBEAT }}
		});
		var billboard = $('#billboard');

		$("#text_message").keydown(function(event) {
			if (event.keyCode === 13) {
				event.preventDefault();
				sendMessage();
			}
		});

		$('#send_message').click(sendMessage);

		// send message to the server using Ajax
		function sendMessage() {
			$.post('{% url "user_chat" %}', {
				user: $('#user').val(),
				message: $('#text_message').val()
			});
		}

		// receive a message though the Websocket from the server
		function receiveMessage(msg) {
			billboard.append('<br/>' + msg);
			billboard.scrollTop(billboard.scrollTop() + 25);
		}
	});
</script>
{% endblock script_panel %}
